package net.lab1024.smartadmin.module.weapp.visitor;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import net.lab1024.smartadmin.common.constant.ResponseCodeConst;
import net.lab1024.smartadmin.common.domain.PageResultDTO;
import net.lab1024.smartadmin.common.domain.ResponseDTO;
import net.lab1024.smartadmin.common.weixin.AddToMessageQueue;
import net.lab1024.smartadmin.module.support.file.service.FileService;
import net.lab1024.smartadmin.module.support.idgenerator.IdGeneratorService;
import net.lab1024.smartadmin.module.support.idgenerator.constant.IdGeneratorEnum;
import net.lab1024.smartadmin.module.system.department.DepartmentDao;
import net.lab1024.smartadmin.module.system.department.domain.dto.DepartmentVO;
import net.lab1024.smartadmin.module.system.department.domain.entity.DepartmentEntity;
import net.lab1024.smartadmin.module.system.employee.EmployeeDao;
import net.lab1024.smartadmin.module.system.employee.domain.dto.CpUserDTO;
import net.lab1024.smartadmin.module.system.employee.domain.dto.EmployeeDTO;
import net.lab1024.smartadmin.module.system.employee.domain.entity.EmployeeEntity;
import net.lab1024.smartadmin.module.system.login.domain.RequestTokenBO;
import net.lab1024.smartadmin.module.system.position.PositionDao;
import net.lab1024.smartadmin.module.system.position.domain.dto.PositionRelationQueryDTO;
import net.lab1024.smartadmin.module.system.position.domain.dto.PositionRelationResultDTO;
import net.lab1024.smartadmin.module.system.privilege.service.PrivilegeEmployeeService;
import net.lab1024.smartadmin.module.system.systemconfig.SystemConfigService;
import net.lab1024.smartadmin.module.system.systemconfig.constant.SystemConfigEnum;
import net.lab1024.smartadmin.module.system.systemconfig.domain.dto.SystemConfigDTO;
import net.lab1024.smartadmin.module.weapp.message.MessageDao;
import net.lab1024.smartadmin.module.weapp.orders.OrdersResponseCodeConst;
import net.lab1024.smartadmin.module.weapp.orders.dao.CommentDao;
import net.lab1024.smartadmin.module.weapp.orders.dao.DetailDao;
import net.lab1024.smartadmin.module.weapp.orders.dao.LikesDao;
import net.lab1024.smartadmin.module.weapp.orders.dao.OrdersDao;
import net.lab1024.smartadmin.module.weapp.orders.domain.dto.*;
import net.lab1024.smartadmin.module.weapp.orders.domain.entity.*;
import net.lab1024.smartadmin.module.weapp.orders.domain.vo.*;
import net.lab1024.smartadmin.module.weapp.orderstype.dao.WorkOrderTypeDao;
import net.lab1024.smartadmin.module.weapp.orderstype.domain.entity.WorkOrderTypeEntity;
import net.lab1024.smartadmin.module.weapp.orderstype.domain.vo.WorkOrderTypeVO;
import net.lab1024.smartadmin.module.weapp.users.dao.UsersDao;
import net.lab1024.smartadmin.module.weapp.users.domain.vo.UsersVO;
import net.lab1024.smartadmin.util.SmartBeanUtil;
import net.lab1024.smartadmin.util.SmartPageUtil;
import net.lab1024.smartadmin.util.SmartRequestTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.text.Position;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * [  ]
 *
 * @author wuqian
 * @version 1.0
 * @company 五千
 * @copyright (c)  五千Inc. All rights reserved.
 * @date 2021-03-10 15:12:30
 * @since JDK1.8
 */
@Service
public class VisitorService {
    @Value("${file-upload-service.path}")
    private String fileParentPath;
    @Autowired
    private VisitorDao visitorDao;

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private AddToMessageQueue addToMessageQueue;

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private PositionDao positionDao;
    /**
     * 根据id查询
     */
    public ResponseDTO<VisitorVO> getById(Long id) {
        VisitorEntity visitorEntity = visitorDao.selectById(id);
        if (visitorEntity == null) {
            return ResponseDTO.wrap(OrdersResponseCodeConst.ORDERS_NOT_EXISTS);
        }

        VisitorVO visitorVO = SmartBeanUtil.copy(visitorEntity,VisitorVO.class);
        DepartmentEntity d = new DepartmentEntity();
        EmployeeDTO employeeDTO = employeeDao.getEmployeeById(visitorVO.getTuid());
        d.setId(employeeDTO.getDepartmentId());
        visitorVO.setDepartmentName(departmentDao.selectById(d).getName());

        Long sessionUid = SmartRequestTokenUtil.getRequestUser().getRequestUserId();
        boolean iscanShow = false;
//        if(visitorEntity.getStep() == 1){
            //等待行政审核状态

            PositionRelationQueryDTO pr = new PositionRelationQueryDTO();
            pr.setEmployeeId(sessionUid);
            pr.setPositionId(20L);
            List<PositionRelationResultDTO> plist = positionDao.selectRelation(pr);
            if(!plist.isEmpty()){
                //当前人是行政人员
                visitorVO.setIsReviewer(true);
                iscanShow = true;
            }

//        }

//        if(visitorEntity.getStep() == 2 || visitorEntity.getStep() == 3|| visitorEntity.getStep() == 4){
            //等待门卫验证
            PositionRelationQueryDTO pr1 = new PositionRelationQueryDTO();
            pr1.setEmployeeId(sessionUid);
            pr1.setPositionId(21L);
            List<PositionRelationResultDTO> plist1 = positionDao.selectRelation(pr1);
            if(!plist1.isEmpty()){
                //当前人是门卫
                visitorVO.setIsSurer(true);
                iscanShow = true;
            }
//        }



        if(visitorEntity.getCreateUid().equals(sessionUid)){
            //是创建人
            iscanShow = true;
        }
        if(visitorEntity.getTuid() == sessionUid){
            //是被拜访人
            iscanShow = true;
            if(visitorVO.getStep() == 1 &&
                    visitorVO.getTuid() != visitorEntity.getCreateUid() &&
                    visitorEntity.getReviewTime2() == null
            ) {
                visitorVO.setIsReviewer(true);
            }
        }

//        if(visitorEntity.getStep() == 0 && !visitorEntity.getCreateUid().equals(sessionUid)){
//            iscanShow = false;
//        }
        if(!iscanShow){
            return ResponseDTO.wrap(OrdersResponseCodeConst.HAND_NOT_AUTH);
        }
        return ResponseDTO.succData(visitorVO);
    }

    /**
     * 分页查询
     * @author wuqian
     * @date 2021-03-10 15:12:30
     */
    public ResponseDTO<PageResultDTO<VisitorVO>> queryByPage(VisitorQueryDTO queryDTO) {
        Page page = SmartPageUtil.convert2QueryPage(queryDTO);

//        Long departmentId = SmartRequestTokenUtil.getRequestUser().getEmployeeBO().getDepartmentId();
        Long isStaff = Long.valueOf(SmartRequestTokenUtil.getRequestUser().getRequestUserId());
//        queryDTO.setDepartmentId(departmentId);
//        if(!SmartRequestTokenUtil.getRequestUser().getEmployeeBO().getIsSuperman()) {
//            queryDTO.setSessionid(SmartRequestTokenUtil.getRequestUserId());
//        }
        queryDTO.setCreateUid(isStaff);
        queryDTO.setTuid(isStaff);
        IPage<VisitorVO> voList = visitorDao.queryByPage(page, queryDTO);
        PageResultDTO<VisitorVO> pageResultDTO = SmartPageUtil.convert2PageResult(voList);
        return ResponseDTO.succData(pageResultDTO);
    }

    /**
     * 添加
     * @author wuqian
     * @date 2021-03-10 15:12:30
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<Long> add(VisitorAddDTO addDTO) {
        RequestTokenBO requestTokenBO = SmartRequestTokenUtil.getRequestUser();
//        Long sessionUid = Long.valueOf(SmartRequestTokenUtil.getRequestUser().getRequestUserId());
        VisitorEntity entity = SmartBeanUtil.copy(addDTO, VisitorEntity.class);
        entity.setIsEat(addDTO.getIsEat()?1:0);
        entity.setIsepidemicrisk(addDTO.getIsepidemicrisk()?1:0);
        entity.setCreateUid(requestTokenBO.getRequestUserId());
        entity.setIsCar(addDTO.getIsCar()?1:0);

        EmployeeDTO em3 = employeeDao.getEmployeeById(entity.getTuid());
        entity.setTname(em3.getActualName());

        entity.setStep(1);//提交审核
        visitorDao.insert(entity);

        //判断申请人为被访人
        if(entity.getTuid() == entity.getCreateUid()){
            //=====》是
            //发送新的访客审核信息
            PositionRelationQueryDTO pr = new PositionRelationQueryDTO();
    //        pr.setEmployeeId(sessionUid);
            pr.setPositionId(20L);
            List<PositionRelationResultDTO> plist = positionDao.selectRelation(pr);
            for(PositionRelationResultDTO postR:plist){
                EmployeeEntity em2 = employeeDao.selectById(postR.getEmployeeId());
                addToMessageQueue.addMinMessage(entity,em2,0);
            }
        }else {
            //=====》否
            //发生给 被访人审核
            EmployeeEntity em2 = employeeDao.selectById(entity.getTuid());
            addToMessageQueue.addMinMessage(entity,em2,0);
        }

        return ResponseDTO.succData(entity.getId());
    }


    /**
     * 编辑
     * @author wuqian
     * @date 2021-03-10 15:12:30
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<Long> update(VisitorAddDTO updateDTO) {

        RequestTokenBO requestTokenBO = SmartRequestTokenUtil.getRequestUser();
        VisitorEntity entity = SmartBeanUtil.copy(updateDTO, VisitorEntity.class);
        entity.setIsEat(updateDTO.getIsEat() ? 1 : 0);
        entity.setIsepidemicrisk(updateDTO.getIsepidemicrisk() ? 1 : 0);

        if (entity.getTuid() != null){
            EmployeeDTO em3 = employeeDao.getEmployeeById(entity.getTuid());
            entity.setTname(em3.getActualName());
        }

        entity.setStep(entity.getStep()+1);
        visitorDao.updateById(entity);
        return ResponseDTO.succData(entity.getId());
    }
//
//    /**
//     * 删除
//     * @author wuqian
//     * @date 2021-03-10 15:12:30
//     */
//    @Transactional(rollbackFor = Exception.class)
//    public ResponseDTO<String> deleteByIds(List<Long> idList) {
//        ordersDao.deleteByIdList(idList);
//        return ResponseDTO.succ();
//    }
//
//    /**
//     * 查询全部导出对象
//     * @author wuqian
//     * @date 2021-03-10 15:12:30
//     */
//    public List<OrdersExcelVO> queryAllExportData(OrdersQueryDTO queryDTO) {
//        return ordersDao.queryAllExportData( queryDTO);
//    }
//
//    /**
//     * 批量查询导出对象
//     * @author wuqian
//     * @date 2021-03-10 15:12:30
//     */
//    public List<OrdersExcelVO> queryBatchExportData(List<Long> idList) {
//        return ordersDao.queryBatchExportData(idList);
//    }
//
//    /**
//     * 点赞处理
//     * @param id
//     * @return
//     */
//    @Transactional(rollbackFor = Exception.class)
//    public ResponseDTO<String> upLike(Long id) {
//
//        OrdersLikeEntity ordersLikeEntity = new OrdersLikeEntity();
//        ordersLikeEntity.setCreateUid(SmartRequestTokenUtil.getRequestUserId());
//        ordersLikeEntity.setOid(id);
//
//        ordersLikeEntity.setCreateTime(new Date());
//        ordersLikeEntity.setUpdateTime(new Date());
//        likeDao.addLike(ordersLikeEntity);
//        return ResponseDTO.succ();
//    }
//
    /**
     * 工单切换 一级管理人
     * @param handDTO
     * @return
     */
    public ResponseDTO<String> hand(VisitorHandleDTO handDTO) {
        Long sessionId = SmartRequestTokenUtil.getRequestUserId();
        VisitorEntity visitorEntity = visitorDao.selectById(handDTO.getId());
        if(handDTO.getActype().equals("1")){
            if(visitorEntity.getStep() == 1 ){
                //判断是否被访人审核
                if(visitorEntity.getTuid() == sessionId){
                    //===> 被访人审核  发消息给 行政
                    //被访人审核  下一个节点行政
                    visitorEntity.setReviewTime2(new Date());
                    PositionRelationQueryDTO pr = new PositionRelationQueryDTO();
                    pr.setPositionId(20L);
                    List<PositionRelationResultDTO> plist = positionDao.selectRelation(pr);
                    for(PositionRelationResultDTO postR:plist){
                        EmployeeEntity em2 = employeeDao.selectById(postR.getEmployeeId());
                        addToMessageQueue.addMinMessage(visitorEntity,em2,0);
                    }
                }else {
                    //行政审核
                    visitorEntity.setStep(visitorEntity.getStep() + 1);
                    visitorEntity.setReviewTime(new Date());
                    visitorEntity.setReviewUid(sessionId);
                    //发送审核通过提醒消息给被拜访人
                    EmployeeEntity em2 = employeeDao.selectById(visitorEntity.getCreateUid());
                    if (em2.getUserId() == null) {
                        em2 = employeeDao.selectById(visitorEntity.getTuid());
                    }
                    addToMessageQueue.addMinMessage(visitorEntity, em2, 1);

                    //发送消息给保安队长
                    PositionRelationQueryDTO pr = new PositionRelationQueryDTO();
                    pr.setPositionId(22L);
                    List<PositionRelationResultDTO> plist = positionDao.selectRelation(pr);
                    for(PositionRelationResultDTO postR:plist){
                        EmployeeEntity em3 = employeeDao.selectById(postR.getEmployeeId());
                        addToMessageQueue.addMinMessage(visitorEntity,em3,1);
                    }
                }
            }
            //审核同意
            else if(visitorEntity.getStep() == 2 ){
                //门卫确认进场
                visitorEntity.setStep(visitorEntity.getStep()+1);
                visitorEntity.setGotime(new Date());
                visitorEntity.setSureTime(new Date());
                visitorEntity.setSureUid(sessionId);
                //发送审核通过提醒消息给被拜访人
                EmployeeEntity em2 = employeeDao.selectById(visitorEntity.getCreateUid());
                if(em2.getUserId() == null){
                    em2 = employeeDao.selectById(visitorEntity.getTuid());
                }
                addToMessageQueue.addMinMessage(visitorEntity,em2,2);
            }
            else if(visitorEntity.getStep() == 3){
                //门卫确认离开
                visitorEntity.setStep(visitorEntity.getStep()+1);
                visitorEntity.setLeavetime(new Date());
                visitorEntity.setSureTime2(new Date());
                visitorEntity.setSureUid2(sessionId);
                //发送审核通过提醒消息给被拜访人
                EmployeeEntity em2 = employeeDao.selectById(visitorEntity.getCreateUid());
                if(em2.getUserId() == null){
                    em2 = employeeDao.selectById(visitorEntity.getTuid());
                }
                addToMessageQueue.addMinMessage(visitorEntity,em2,3);
            }

        }
        if(handDTO.getActype().equals("2")){
            //审核拒绝
            if(visitorEntity.getStep() == 1 ){
                //行政审核
                visitorEntity.setStep(0);
                visitorEntity.setReviewTime(new Date());
                visitorEntity.setReviewUid(sessionId);
                //发送审核通过提醒消息给 信息创建人
                EmployeeEntity em2 = employeeDao.selectById(visitorEntity.getCreateUid());
                if(em2.getUserId() == null){
                    em2 = employeeDao.selectById(visitorEntity.getTuid());
                }
                addToMessageQueue.addMinMessage(visitorEntity,em2,4);
            }
            //审核拒绝
            else if(visitorEntity.getStep() == 2 ){
                //门卫审核 拒绝
                visitorEntity.setStep(0);
                visitorEntity.setSureTime(new Date());
                visitorEntity.setSureUid(sessionId);
                //发送审核通过提醒消息给被拜访人
                EmployeeEntity em2 = employeeDao.selectById(visitorEntity.getCreateUid());
                if(em2.getUserId() == null){
                    //优先发送消息给信息创建人，如提交信息未外部人员， 者发送给拜访人
                    em2 = employeeDao.selectById(visitorEntity.getTuid());
                }
                addToMessageQueue.addMinMessage(visitorEntity,em2,5);
            }

        }
        visitorEntity.setReComments(handDTO.getOpinion());
        visitorDao.updateById(visitorEntity);

        return ResponseDTO.succ();
    }

    public ResponseDTO<String> getshareqr(Long id) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        String filePath = "qr/"+new Date().getYear()+"/";
        File directory = new File(fileParentPath+filePath);
        if (!directory.exists()) {
            // 目录不存在，新建
            directory.mkdirs();
        }
        BitMatrix bitMatrix = null;

        filePath += id+".png";
        bitMatrix = qrCodeWriter.encode("https://itil.bio-ss.net/fangkeqr/"+id, BarcodeFormat.QR_CODE, 80, 80);
        Path path = FileSystems.getDefault().getPath(fileParentPath+filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

        return ResponseDTO.succData("https://itil.bio-ss.net/upload/"+filePath);
    }
}